import axios from 'axios';
import { baseUrl } from '@/utils/env.js';
import router from '@/router';
import { Message } from 'element-ui';

// 添加请求头
const instance = axios.create({
  withCredentials: true,
  baseURL: baseUrl, // 请求地址的基础路径
  timeout: 10000 // 请求超时时间
});

// 通过拦截器格式化参数
instance.interceptors.request.use(config => {
  // post请求就格式化数据
  if (config.method === 'post') {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  }
  return config;
}, function(error) {
  return Promise.reject(error);
});

export default (url = '', data = {}, type = 'POST', responseType = 'json', headers = {}) => {
  return new Promise((resolve, reject) => {
    let httpPromise = null;
    if (type.toUpperCase() === 'GET') {
      httpPromise = instance({
        method: type,
        url: url,
        params: data,
        headers,
        responseType,
      });
    } else {
      httpPromise = instance({
        method: type,
        url: url,
        data: data,
        headers,
        responseType,
      });
    }
    httpPromise.then(res => {
      // 处理返回的文件流
      // 通过a标签实现文件的下载
      if (responseType === 'blob') {
        const content = res.data;
        const elink = document.createElement('a'); // 创建a标签
        // 获取文件名,根据后端返回不同获取的字段不同
        elink.download = decodeURI(escape(res.headers['content-disposition'].split('=')[1]));
        elink.style.display = 'none';
        const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=UTF-8' });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 触发点击a标签事件
        document.body.removeChild(elink);
        resolve();
      } else {
        if (res.data.ret === 0) {
          resolve(res.data);
        } else if (res.data.ret === 101) {
          // 没有登录
          router.push({ path: '/login' });
          return;
        } else {
          // throw new Error(res.message || '请求失败，请联系开发者！')
          Message.error(res.message || '请求失败，请联系开发者！');
        }
      }
    }).catch(err => {
      let errMsg = '请求失败';
      if (err.response && err.response.status === 500) {
        errMsg = '服务器开小差了~';
      } else if (err.code === 'ECONNABORTED') {
        errMsg = '请求超时';
      }
      reject(new Error(errMsg));
    });
  });
};
